import gradio as gr
import pandas as pd

import matplotlib
import matplotlib.pyplot as plt


# 设置全局字体为支持中文的字体
matplotlib.rcParams['font.sans-serif'] = ['SimHei']  # 或者使用 'Microsoft YaHei'
matplotlib.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题


def get_items(data):
    cols = data.columns.to_list()
    aa, bb, cc = [], [], []
    for k in cols:
        k_li = k.split('_')
        aa.append(k_li[0])
        bb.append(k_li[1])
        cc.append(k_li[2])
    return list(set(aa)), list(set(bb)), list(set(cc))


class ShowData:
    """
    """

    def __init__(self):
        self.data = data = pd.read_excel('非金融资金流量表_统计局.xlsx', index_col=0)
        self.a, self.b, self.c = get_items(data)
    
    def value_added(self, item):
        vava = f"{item}_来源_二、增加值"
        
        labor_in = f"{item}_来源_三、劳动者报酬"
        labor_out = f"{item}_运用_三、劳动者报酬"
        capital_in = f"{item}_来源_五、财产收入"
        capital_out = f"{item}_运用_五、财产收入"
        tax_in = f"{item}_来源_四、生产税净额"
        tax_out = f"{item}_运用_四、生产税净额"
        for i in [labor_in, labor_out, capital_in, capital_out, tax_in, tax_out]:
            print(self.data[i])
        return ''
    
    def update_img(self, a, b, c):
        item = f"{a}_{b}_{c}"
        se = self.data[item]
        categories = se.index.to_list()
        categories = [i.replace('年', '')[2:] for i in categories]
        values = se.to_list()
        fig, ax = plt.subplots(figsize=(10, 5))
        bars = ax.bar(categories, values)
        for bar in bars:
            height = bar.get_height()
            height_ = height / 10000
            ax.annotate(f"{height_ :.1f}",
                        xy=(bar.get_x() + bar.get_width() / 2, height),
                        xytext=(0, 3),
                        textcoords="offset points", ha='center', va='bottom')
        ax.set_title(f"资金流量 >>{item}")
        addr = f"cach_img/{item}.png"
        fig.savefig(addr)
        return addr
    
    def update_img2(self, a):
        return ''
        
    
    def page(self):
        with gr.Blocks() as demo:
            gr.Markdown("# 资金流量表数据查询")
            with gr.Row():
                with gr.Column(scale=1):
                    a_select = gr.Dropdown(label="部门", choices=self.a, value=self.a[0])
                    b_select = gr.Dropdown(label="来源或运用", choices=self.b, value=self.b[0])
                    c_select = gr.Dropdown(label="项目", choices=self.c, value=self.c[0])
                with gr.Column(scale=2):
                    imgs = gr.Image(label='show')
                
                a_select.change(self.update_img, inputs=[a_select, b_select, c_select], outputs=imgs)
                b_select.change(self.update_img, inputs=[a_select, b_select, c_select], outputs=imgs)
                c_select.change(self.update_img, inputs=[a_select, b_select, c_select], outputs=imgs)
            gr.Markdown("## 说明：")
            gr.Markdown("### 初次分配：")
            with gr.Row():
                with gr.Column(scale=1):
                    aa_select = gr.Dropdown(label="部门", choices=self.a, value=self.a[0])
                with gr.Column(scale=2):
                    imgs2 = gr.Image(label='show')
                    aa_select.change(self.update_img, inputs=[aa_select], outputs=imgs2)
        return demo        
        
    
if __name__ == '__main__':
    app = ShowData()
    print(app.a)
    print(app.b)
    print(app.c)
    # app.page().launch()